import {designPage, iMouseEvent, reactive, useStyles} from "@peryl/react-compose";
import {unit} from "@peryl/utils/unit";
import {addWindowListener} from "@peryl/utils/addWindowListener";
import {createEffects} from "@peryl/utils/createEffects";

export const DragDemo = designPage(() => {

  const state = reactive({
    top: 0,
    left: 0,
  });

  const styles = useStyles(style => {
    style.position = 'relative';
    style.top = unit(state.top);
    style.left = unit(state.left);

    style.backgroundColor = 'var(--pl-primary-6)';
    style.width = '50px';
    style.height = '50px';

  });

  const onMousedown = (e: iMouseEvent) => {
    const current = { x: state.left, y: state.top };
    const start = { x: e.clientX, y: e.clientY };
    const { effects } = createEffects();
    effects.push(
      addWindowListener('mousemove', (e) => {
        console.log('moving', e.clientX, e.clientY);
        const durX = e.clientX - start.x;
        const durY = e.clientY - start.y;
        state.left = current.x + durX;
        state.top = current.y + durY;
      })
    );
    effects.push(addWindowListener('mouseup', effects.clear));
  };

  return () => (
    <div>
      <div style={styles.value} onMouseDown={onMousedown}>

      </div>
    </div>
  );
});
